import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  message,
  Select,
  Radio,
  Tree,
  Tag,
  Tabs,
} from 'antd';
import SelectDetailModal from './components/selectDetail';
import TagsBlock from './components/tagsBlock';
import SpecialBlockList from './components/specialBlockList';
import { history } from 'umi';
import {
  filterAssignArr,
  formatTreeData,
  formatStatusMap,
  getStorageData,
} from '@/utils/tools';

import styles from './index.less';

import { SpecialData } from './types/interface';
import {
  getOrgTree,
  getSpecialLabelList,
  getUserRoleList,
  saveUser,
  getByMgtorg,
  userDetailsById,
  updateUser,
  getMenuByScope,
} from '@/services/userControl';

import { orgGetOne } from '@/services/common';

import { getStatusMap } from '@/services/common';
import Modal from 'antd/lib/modal/Modal';

export default (props: any) => {
  const {
    state: { pageType, userId },
  } = props.location;
  console.log(props);
  const formRef = useRef<any>();
  const [loginUserType, setloginUserType] = useState<number>();
  const [workDepartmentTreeMsg, setworkDepartmentTreeMsg] = useState({
    dataSource: [],
    defaultExpandedKeys: [],
    checkedKeys: [],
  });
  const [manageDepartmentList, setManageDepartmentList] = useState([]);
  const [manageDepartmentCheckKeys, setmanageDepartmentCheckKeys] = useState(
    [],
  );
  const [nameList, setnameList] = useState([]);
  const [userTypeRadio, setuserTypeRadio] = useState({});
  const [userStatusRadio, setuserStatusRadio] = useState({});
  const [employeeMsg, setemployeeMsg] = useState({});

  const [saveLoading, setsaveLoading] = useState(false);

  const [roleMsg, setRoleMsg] = useState({
    allRoleList: [],
    checkRoleList: [],
    checkRoleKeys: [],
  });
  const [manageDepartmentShow, setmanageDepartmentShow] = useState(false);
  const [workCheckedKeys, setworkCheckedKeys] = useState([]);

  const [departmentShow, setdepartmentShow] = useState(false);
  const [functionAuthorizationShow, setfunctionAuthorizationShow] = useState(
    false,
  );

  const [systemMenu, setsystemMenu] = useState([]);

  const [addAuthorizationModalMsg, setaddAuthorizationModalMsg] = useState({
    visible: false,
    title: '',
  });

  const [specialDataList, setspecialDataList] = useState<SpecialData[]>([]);

  const [usedModal, setusedModal] = useState(false);

  useEffect(async () => {
    setsaveLoading(true);
    setloginUserType(getStorageData('userInfo').userType);
    await getRadioMap(); //用户类型 用户状态
    await getByMgtorgData(); //人员
    await getSpecialLabel(); //特殊
    const manageRes = await getManageDepartmentList();
    await getWorkDepartmentTree([]); //工作机构
    if (pageType !== 'add') {
      await getUserDetailsById(manageRes);
    }
    setsaveLoading(false);
  }, []);

  const getUserDetailsById = async (nameList) => {
    const res = await userDetailsById(userId);
    setdepartmentShow(true);
    const data = res?.data;
    console.log('getUserDetailsById', data);
    const lastData = {
      ...data,
      userType: data.type,
      userState: data.status,
    };
    console.log(lastData, nameList);
    let employeeMsg =
      nameList.filter((item) => item.id === lastData?.employeeId)[0] || {};
    console.log(employeeMsg);
    setemployeeMsg(employeeMsg);
    let manageKeys = new Set(lastData?.userManageOrganization).add(
      employeeMsg?.orgId,
    );
    let workCheckSet = new Set(lastData.userWorkForOrganization).add(
      employeeMsg.oneLevelId,
    );
    setworkCheckedKeys(Array.from(workCheckSet) as any);
    // setworkDepartmentTreeMsg({
    //   ...workDepartmentTreeMsg,
    //   checkedKeys: Array.from(workCheckSet) as any,
    // });
    getWorkDepartmentTree(Array.from(workCheckSet),employeeMsg?.oneLevelId)
    setmanageDepartmentCheckKeys(Array.from(manageKeys) as any);
    // getRoleListByWorkOrgIdList(userId, Array.from(workCheckSet) as any);
    setspecialDataList(lastData.labels); //特殊数据赋值
    formRef.current.setFieldsValue(lastData);
    if (lastData.userType === 2) {
      //管理员 展示管理机构树
      setmanageDepartmentShow(true);
    }
    return data;
  };
  const getRadioMap = async () => {
    const userTypeRadio = await getStatusMap('sys_user_type');
    const userStatusRadio = await getStatusMap('sys_common_status');
    setuserTypeRadio(formatStatusMap(userTypeRadio.data) as any);
    setuserStatusRadio(formatStatusMap(userStatusRadio.data) as any);
  };

  const getByMgtorgData = async () => {
    let params = pageType === 'add' ? { flag: 1, status: 1 } : {};

    const res = await getByMgtorg(params);
    console.log(res);
    setnameList(res.data);
  };
  const changeEmployee = async (id) => {
    let employeeMsg = nameList.filter((item) => item.id === id)[0];
    console.log(employeeMsg);
    setemployeeMsg(employeeMsg);

    setmanageDepartmentCheckKeys([employeeMsg.oneLevelId]);
    // await getManageDepartmentList(employeeMsg?.oneLevelId); //管理机构
    getWorkDepartmentTree([employeeMsg?.orgId],employeeMsg?.orgId); //工作机构
    // getRoleListByWorkOrgIdList(userId, workCheckedKeys);
    setdepartmentShow(true);
  };

  const getManageDepartmentList = async () => {
    // 根据接口获取值
    const res = await orgGetOne({ isScope: 1 });
    let arr = [];
    for (const item of res.data) {
      arr.push({
        label: item.name,
        value: item.id,
      });
    }
    setManageDepartmentList(arr);
    return arr;
  };

  //
  const getWorkDepartmentTree = async (workCheckedKeys, orgId = -1) => {
    const workRes = await getOrgTree({ orgType: 0 });
    console.log(workCheckedKeys,orgId)
    // let lastWorkCheckedKeys = [...workCheckedKeys,orgId] as any;
    // if (pageType !== 'add') {
    //   const userDetails = await getUserDetailsById();
    //   console.log(userDetails);
    //   let workCheckSet = new Set(userDetails.userWorkForOrganization).add(
    //     employeeMsg.orgId,
    //   );
    //   console.log(workCheckSet);
    //   workCheckedKeys = Array.from(workCheckSet);
    //   console.log(workCheckedKeys);
    //   setspecialDataList(userDetails.labels);
    // }
    setworkDepartmentTreeMsg({
      dataSource: formatWorkDepartmentTreeData(workRes?.data, orgId),
      defaultExpandedKeys: [workRes?.data[0]?.key] as any,
      checkedKeys: workCheckedKeys,
    });
    if(workCheckedKeys.length > 0){
      getRoleListByWorkOrgIdList(userId, workCheckedKeys);
    }
    return workRes;
  };

  const formatWorkDepartmentTreeData = (data, orgId) => {
    if (Array.isArray(data) && data.length > 0) {
      data.forEach((ele) => {
        ele.title = ele.name;
        ele.key = ele.id;
        if (ele.id === orgId) {
          ele.disabled = true;
        }
        if (ele.children && ele.children.length > 0) {
          formatWorkDepartmentTreeData(ele.children, orgId);
        }
      });
    }
    return data;
  };
  const manageDepartmentChange = (ids) => {
    setmanageDepartmentCheckKeys(ids);
  };
  //角色授权组件数据
  const getRoleListByWorkOrgIdList = async (
    userId: string | number,
    workCheckKeys: React.Key[],
  ) => {
    let msg = {
      userId,
      workOrgIdList: workCheckKeys.filter(Boolean),
    };
    const res = await getUserRoleList(msg);
    console.log(res);
    const { allRoleList, authorizedRoleList } = res.data;
    // getSystemMenuByRoleId(authorizedRoleList || []);
    setRoleMsg({
      allRoleList: formatRoleList(allRoleList),
      checkRoleList: formatRoleList(authorizedRoleList),
      checkRoleKeys: formatRoleList(authorizedRoleList).map(
        (item) => item.value,
      ),
    });
    setfunctionAuthorizationShow(true);
  };

  const getSystemMenuByRoleId = async (roleList) => {
    let lastIdList = roleList.map((item) => item.value);
    const params = {
      contain: 1,
      idList: lastIdList,
      scope: 3,
      idType: 3,
    };
    const res = await getMenuByScope(params);
    setsystemMenu(formatTreeData(res?.data));
  };
  const removeCurrentTagHandle = (val: string) => {
    console.log(val, roleMsg);
    const newTags = roleMsg.checkRoleList.filter((item) => item.value !== val);
    setRoleMsg({
      ...roleMsg,
      checkRoleList: newTags,
      checkRoleKeys: newTags.map((item: any) => item.value),
    });
  };

  const btnGroupDom = (
    <>
      <Button
        disabled={pageType === 'details'}
        onClick={() => {
          setaddAuthorizationModalMsg({
            ...addAuthorizationModalMsg,
            title: '角色授权',
            visible: true,
          });
        }}
      >
        添加
      </Button>
      <Button
        style={{ marginLeft: '8px' }}
        onClick={() => {
          setusedModal(true);
        }}
      >
        查看可使用的功能
      </Button>
    </>
  );

  const formatRoleList = (data: any[]) => {
    const arr = [];
    if (Array.isArray(data) && data.length > 0) {
      for (const item of data) {
        arr.push({
          value: item.id,
          label: `${item.organizationName}（${item.roleName}）`,
        });
      }
    }
    return arr;
  };

  const getSpecialLabel = async () => {
    const res = await getSpecialLabelList({});
    console.log(res);
    setspecialDataList(res.data);
  };
  const specialRemoveHandle = useCallback(
    (id, data) => {
      const newSpecialData = specialDataList.filter((item) => item.id !== id);
      setspecialDataList(newSpecialData);
    },
    [specialDataList],
  );
  const addEditSpecialDataHandle = useCallback(
    (type, data) => {
      console.log(type, data);
      setspecialDataList(data);
    },
    [specialDataList],
  );

  const filterSpecialData = (data: any[]) => {
    let arr = [];
    for (const item of data) {
      if (item.selected) {
        let valueIds = [],
          values = [];
        for (const item2 of item.labelValues) {
          if (item2.selected) {
            valueIds.push(item2.id);
            values.push(item2.value);
          }
        }
        arr.push({
          sysLabelId: item.id,
          valueIds,
          values,
        });
      }
    }
    return arr;
  };
  const saveData = async () => {
    setsaveLoading(true);
    console.log(11111);
    try {
      console.log(2222);
      const values = await formRef.current.validateFields();
      filterSpecialData(specialDataList);
      let id = pageType !== 'add' ? { id: userId } : {};
      let userManageOrganizationKeys =
        values.userType === 2
          ? { userManageOrganization: manageDepartmentCheckKeys.filter(Boolean) }
          : {};
      let msg = {
        ...id,
        name: values.name,
        status: values.userState + '',
        type: values.userType + '',
        employeeId: values.employeeId,
        roles: roleMsg.checkRoleKeys,
        ...userManageOrganizationKeys,
        userWorkForOrganization: workDepartmentTreeMsg.checkedKeys.filter(Boolean),
        labels: filterSpecialData(specialDataList),
      };
      console.log(msg);
      let saveRes;
      if (pageType === 'add') {
        saveRes = await saveUser(msg);
      } else {
        saveRes = await updateUser(msg);
      }
      console.log(saveRes);
      setsaveLoading(false);
      if (saveRes.code === 200) {
        message.success('保存成功');
        setTimeout(() => {
          history.push({
            pathname: '/features/userPermission/user/index',
          });
        }, 1000);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
      setsaveLoading(false);
    }
  };
  return (
    <>
      {addAuthorizationModalMsg.visible && (
        <SelectDetailModal
          visible={addAuthorizationModalMsg.visible}
          title={addAuthorizationModalMsg.title}
          dataSource={roleMsg.allRoleList}
          checkKeys={roleMsg.checkRoleKeys}
          handleOkCallback={(keys, tagsData) => {
            console.log(tagsData);
            setRoleMsg({
              ...roleMsg,
              checkRoleList: tagsData,
              checkRoleKeys: tagsData.map((item: any) => item.value),
            });
            getSystemMenuByRoleId(tagsData);
            setaddAuthorizationModalMsg({
              ...addAuthorizationModalMsg,
              visible: false,
            });
          }}
          handleCancelCallback={() => {
            setaddAuthorizationModalMsg({
              ...addAuthorizationModalMsg,
              visible: false,
            });
          }}
        ></SelectDetailModal>
      )}
      <Modal
        title="查看可使用功能"
        visible={usedModal}
        width={'65%'}
        cancelText={'取消'}
        onCancel={() => {
          setusedModal(false);
        }}
      >
        <div>
          <TagsBlock
            dataSource={roleMsg.checkRoleList}
            closable={pageType !== 'details'}
            simple
          ></TagsBlock>
          <div>
            <Tabs defaultActiveKey={systemMenu[0]?.id}>
              {systemMenu.map((item: any) => (
                <Tabs.TabPane
                  style={{ height: '200px', overflowY: 'auto' }}
                  tab={item?.name}
                  key={item?.id}
                >
                  <Tree treeData={item?.children} />
                </Tabs.TabPane>
              ))}
            </Tabs>
          </div>
        </div>
      </Modal>
      <Card title="基本信息">
        <Form
          ref={formRef}
          onValuesChange={(changedValues, allValues) => {
            let { userType, employeeId } = allValues;
            if (userType === 2) {
              setmanageDepartmentShow(true);
            } else {
              setmanageDepartmentShow(false);
            }
          }}
        >
          <div className={styles.formContainer}>
            <div className={styles.flexRow}>
              <Form.Item
                name="name"
                label="用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入4-32位英文字符不能为空!',
                  },
                  {
                    pattern: /^[a-zA-Z_][0-9a-zA-Z_]{3,30}$/,
                    message: '请输入4-32位英文字符',
                  },
                ]}
              >
                <Input
                  disabled={pageType === 'edit' || pageType === 'details'}
                ></Input>
              </Form.Item>
              <Form.Item
                name="userType"
                label="用户类型"
                rules={[{ required: true, message: '请选择用户类型!' }]}
              >
                <Radio.Group disabled={pageType === 'details'}>
                  {Object.entries(userTypeRadio).map((item: any) => (
                    <Radio
                      key={+item[0]}
                      value={+item[0]}
                      disabled={+item[0] <= loginUserType}
                    >
                      {item[1]}
                    </Radio>
                  ))}
                </Radio.Group>
              </Form.Item>
            </div>
            <div className={styles.flexRow}>
              <Form.Item
                name="employeeId"
                label="人员姓名"
                rules={[{ required: true, message: '请选择人员姓名!' }]}
              >
                <Select
                  disabled={pageType === 'edit' || pageType === 'details'}
                  placeholder="请选择人员姓名"
                  onChange={changeEmployee}
                >
                  {nameList.map((item: any) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}
                      {item.employeeCode && `（${item.employeeCode}）`}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                name="userState"
                label="用户状态"
                rules={[{ required: true, message: '请选择用户状态!' }]}
              >
                <Radio.Group disabled={pageType === 'details'}>
                  {Object.entries(userStatusRadio).map((item) => (
                    <Radio key={+item[0]} value={+item[0]}>
                      {item[1]}
                    </Radio>
                  ))}
                </Radio.Group>
              </Form.Item>
            </div>
            <div className={styles.flexRow}>
              {manageDepartmentShow && (
                <Form.Item name="manageDepartment" label="管理机构">
                  <div className={styles.treeContainer}>
                    {departmentShow ? (
                      <>
                        <div className={styles.treeTitle}>成都民航西南凯亚</div>
                        <div style={{ height: '368px', overflowY: 'auto' }}>
                          {
                            <Checkbox.Group
                              style={{
                                display: 'flex',
                                flexDirection: 'column',
                                padding: '8px',
                              }}
                              disabled={pageType === 'details'}
                              options={manageDepartmentList}
                              value={manageDepartmentCheckKeys}
                              onChange={manageDepartmentChange}
                            />
                          }
                        </div>
                      </>
                    ) : (
                      <span style={{ color: 'red' }}>
                        展示管理机构请选择人员姓名
                      </span>
                    )}
                  </div>
                </Form.Item>
              )}
              <Form.Item name="workDepartment" label="工作机构">
                <div className={styles.treeContainer}>
                  {departmentShow ? (
                    <>
                      <div className={styles.treeTitle}>PSC产品化规范</div>
                      <div>
                        {workDepartmentTreeMsg?.dataSource?.length > 0 &&
                          workDepartmentTreeMsg?.defaultExpandedKeys?.length >
                            0 && (
                            <Tree
                              style={{ height: '368px', overflowY: 'auto' }}
                              disabled={pageType === 'details'}
                              checkable
                              checkStrictly
                              defaultExpandedKeys={
                                workDepartmentTreeMsg.defaultExpandedKeys
                              }
                              checkedKeys={workDepartmentTreeMsg.checkedKeys}
                              onCheck={(
                                checkedKeysValue: any,
                                checkedRow: any,
                              ) => {
                                console.log(checkedKeysValue);
                                let checkKeys = checkedKeysValue.checked;
                                setworkDepartmentTreeMsg({
                                  ...workDepartmentTreeMsg,
                                  checkedKeys: checkKeys,
                                });
                                if (checkKeys.length > 0) {
                                  getRoleListByWorkOrgIdList(userId, checkKeys);
                                } else {
                                  setfunctionAuthorizationShow(false);
                                }
                              }}
                              treeData={workDepartmentTreeMsg.dataSource}
                            />
                          )}
                      </div>
                    </>
                  ) : (
                    <span style={{ color: 'red' }}>
                      展示工作机构请选择人员姓名
                    </span>
                  )}
                </div>
              </Form.Item>
            </div>
            <div className={styles.authorizationContainer}>
              {functionAuthorizationShow ? (
                <div className={styles.functionContainer}>
                  <div className={styles.title}>角色授权</div>
                  <div>
                    <TagsBlock
                      dataSource={roleMsg.checkRoleList}
                      btnGroupDom={btnGroupDom}
                      closable={pageType !== 'details'}
                      removeCurrentTag={removeCurrentTagHandle}
                    ></TagsBlock>
                  </div>
                </div>
              ) : (
                <span style={{ color: 'red' }}>请勾选机构管理节点</span>
              )}

              <div className={styles.specialContainer}>
                <div className={styles.title}>特殊数据授权</div>
                <div>
                  <SpecialBlockList
                    dataSource={specialDataList}
                    pageType={pageType}
                    removeHandleCallback={specialRemoveHandle}
                    addEditSpecialDataHandle={addEditSpecialDataHandle}
                    formDisabled={pageType === 'details'}
                  ></SpecialBlockList>
                </div>
              </div>
            </div>
            <div className={styles.footBtnGroup}>
              <Button
                onClick={() => {
                  history.go(-1);
                }}
              >
                返回
              </Button>
              <Button
                type="primary"
                loading={saveLoading}
                htmlType="submit"
                style={{ marginLeft: '10px' }}
                onClick={saveData}
              >
                保存并提交
              </Button>
            </div>
          </div>
        </Form>
      </Card>
    </>
  );
};
